package com.app.controller.backstage;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.alibaba.fastjson.JSONObject;
import com.app.aspect.Log;
import com.app.common.Result;
import com.app.model.AdminUserModel;
import com.app.model.RoleModel;
import com.app.model.SysLog;
import com.app.service.AdminUserService;
import com.app.service.ISysLogService;
import com.app.service.RoleService;
import com.app.util.CacheUtil;
import com.app.util.CommonHelp;
import com.app.util.IpUtil;
import com.app.util.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.time.LocalDateTime;
import java.util.*;

import static org.apache.commons.codec.digest.DigestUtils.md5Hex;

/*
        后台管理  验证码 返回(key,base64的验证码)  前端返回（key，value）  服务端校验

        完善用户表  接口 用token查用户所有信息和角色关联的管理权限
 */
@Slf4j
@RestController
@RequestMapping("/szwq")
public class AdminController {
    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private ISysLogService iSysLogService;

    // 90 36
    @GetMapping("/captcha")
    public Result<Object> captcha(HttpServletResponse response, HttpServletRequest request) throws Exception {
        response.setHeader("Cache-Control", "no-store,no-cache");
        response.setContentType("image/jpeg");
        //生成文字验证码
        String text = String.format("%04d", new Random().nextInt(9999));
        log.info(text);
        //生成图片验证码
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(90, 36);
        BufferedImage image = (BufferedImage) lineCaptcha.createImage(text);
//        BufferedImage image = producter.createImage(text);
        UUID uuid = UUID.randomUUID();
        //保存验证码到本地缓存
        CacheUtil.put(uuid.toString(), text);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", stream);
        String base64 = Base64.getEncoder().encodeToString(stream.toByteArray());
        JSONObject data = new JSONObject();
        String base666 = "data:image/png;base64," + base64;
        data.put("key", uuid);
        data.put("code", base666);
        return Result.success(data);
    }

    /**
     * 后台登录
     */
    //d810f1d5-58cd-47c8-ab7b-0f2dff5dfcac
    @PostMapping("/adminLogin")
    public Result<Object> userLogin(@RequestBody JSONObject json, HttpServletRequest request) {
        String pwd = json.get("password").toString();
        String key = json.get("key").toString();
        String code = json.get("code").toString();
        String account = json.get("username").toString();
        String salt = "dh_wq";
        String pwd1 = md5Hex(pwd + salt);
        Object code1 = CacheUtil.get(key);
        if (code1 == null) {
            return Result.error(500, "验证码已失效或已过期");
        }
        if (!code1.equals(code)) {
            return Result.error(500, "验证码错误");
        }
        AdminUserModel user = adminUserService.getUserByUserName(account, pwd1);
        if (user == null) {
            return Result.error(500, "用户名或密码错误");
        }
        int status = user.getStatus();
        if (status == 0) {
            return Result.error(500, "该账户已被禁用");
        }
        String token = TokenUtils.sign(String.valueOf(user.getId()));
        String ip = IpUtil.getIpAddress(request);
        user.setToken(token);
        user.setLastIp(ip);
        user.setLastLoginTime(CommonHelp.getNowTimestamp());
        adminUserService.update(user);
        try {
            SysLog sysLog = new SysLog();
            sysLog.setType("2");
            sysLog.setTitle("用户登录");
            sysLog.setUserId(user.getId().toString());
            sysLog.setCreateTime(LocalDateTime.now());
            sysLog.setMethod("POST");
            sysLog.setRemoteAddr(IpUtil.getIpAddress(request));
            sysLog.setIpSources(IpUtil.getIpSource(IpUtil.getIpAddress(request)).toString());
            iSysLogService.insert(sysLog);
        } catch (Exception e) {
            log.info(e.toString());
        }
        return Result.success(user);
    }


    @GetMapping("/getAdminByToken")
    public Result<Object> getAdminByToken(@RequestParam("token") String token,
                                          HttpServletRequest request) {
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        if (userId.equals("false")) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel user = adminUserService.getUserByUserId(Integer.valueOf(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        RoleModel roleModel = roleService.getRoleByRoleId(user.getRoles());
        List<String> roleModelList = new ArrayList<>();
        String[] roleArr = roleModel.getRules().split(";");//获取字符串
        if (roleArr != null) {
            for (int i = 0; i < roleArr.length; i++) {
                roleModelList.add(roleArr[i]);
            }
            user.setPermissionList(roleModelList);
        }

        return Result.success(user);
    }

    /**
     * 后台修改密码  /api/admin/updatePassWord
     */
    @PostMapping("/updatePassWord")
    @Log("后台修改密码")
    public Result<Object> updatePassWord(@RequestBody JSONObject json//新密码
    ) {
        String pwd = (String) json.get("password");
        Integer userId = (Integer) json.get("id");
        AdminUserModel user = adminUserService.getUserById(userId);
        if (user == null) {
            return Result.error(405, "用户不存在");
        }
        String salt = "dh_wq";
        String newWord = md5Hex(pwd + salt);
        user.setPassword(newWord);
        adminUserService.update(user);
        return Result.success("修改成功");
    }


    //管理员管理
    //添加和编辑管理员
    @PostMapping("/insertAndUpdateAdmin")
    @Log("编辑管理员")
    public Result<Object> insertAndUpdateAdmin(@RequestBody AdminUserModel adminUserModel, HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        if (userId.equals("false")) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        String salt = "dh_wq";
        if (adminUserModel.getId() == null || adminUserModel.getId() == 0) {
            String pwd = adminUserModel.getPassword();
            String newWord = md5Hex(pwd + salt);
            adminUserModel.setPassword(newWord);
            adminUserModel.setCreateTime(CommonHelp.getNowTimestamp());
            adminUserService.insertAdmin(adminUserModel);
        } else {
            if (adminUserModel.getPassword() != null) {
                String pwd = adminUserModel.getPassword();
                String newWord = md5Hex(pwd + salt);
                adminUserModel.setPassword(newWord);
            }
            adminUserModel.setUpdateTime(CommonHelp.getNowTimestamp());
            adminUserService.updateAdmin(adminUserModel);
        }
        return Result.success("操作成功");
    }

    //删除管理员
    @GetMapping("/deleteAdmin")
    @Log("删除管理员")
    public Result<Object> deleteAdmin(HttpServletRequest request, Integer id) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        if (userId.equals("false")) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        adminUserService.deleteAdmin(id);
        return Result.success("操作成功");
    }

    //查询
    @GetMapping("/selectAdmin")
    public Result<Object> selectAdmin(HttpServletRequest request, Integer page, Integer limit, String username) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        if (userId.equals("false")) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        return Result.success(adminUserService.selectAdmin(page, limit, username, user.getId()));
    }

    //修改状态
    @GetMapping("/updateUserStatus")
    @Log("修改状态")
    public Result<Object> updateStatus(HttpServletRequest request, Integer status, Integer id) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        if (userId.equals("false")) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        adminUserService.updateStatus(status, id);
        return Result.success("修改成功");
    }

    //fa6eac900ad04087b3deb5f7d9b83879
    public static void main(String[] args) {
        String salt = "dh_wq";
        String pwd1 = md5Hex("123456" + salt);
        System.out.println(pwd1);
    }

    //分配
    @GetMapping("/allocation")
    @Log("分配")
    public Result<Object> allocation(Integer id, Integer adminUserId) {
        adminUserService.allocation(id, adminUserId);
        return Result.success("操作成功");
    }
}
